package com.fubowen.reader.db

import android.app.Application
import android.content.Context
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.Fragment
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.room.Room
import java.util.concurrent.ConcurrentHashMap
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty

private const val DATABASE_NAME = "theme-db"
private var databaseCache = ConcurrentHashMap<String, ThemeDatabase>()

private fun createDatabase(context: Context, databaseName: String) = Room
    .databaseBuilder(context, ThemeDatabase::class.java, databaseName)
    .allowMainThreadQueries()
    .fallbackToDestructiveMigration()
    .fallbackToDestructiveMigrationOnDowngrade()
    .build()

//region 属性委托


class ThemeDatabaseDelegate : ReadOnlyProperty<Fragment, ThemeDatabase> {

    override fun getValue(thisRef: Fragment, property: KProperty<*>): ThemeDatabase {
        return databaseCache.getOrPut(DATABASE_NAME) {
            createDatabase(thisRef.requireContext().applicationContext, DATABASE_NAME)
        }
    }
}

class ViewModelDelegate : ReadOnlyProperty<AndroidViewModel, ThemeDatabase> {

    override fun getValue(thisRef: AndroidViewModel, property: KProperty<*>): ThemeDatabase {
        return databaseCache.getOrPut(DATABASE_NAME) {
            createDatabase(thisRef.getApplication<Application>().applicationContext, DATABASE_NAME)
        }
    }
}
//endregion

val Context.database: ThemeDatabase get() = databaseCache.getOrPut(DATABASE_NAME) { createDatabase(this, DATABASE_NAME) }

fun Fragment.databaseOfTheme() = ThemeDatabaseDelegate()
fun ViewModel.databaseOfTheme() = ViewModelDelegate()

